package com.xjnt.base.support.admin.shiro.permission;

import java.io.Serializable;

import org.apache.shiro.authz.Permission;

public class AbsoluteMatcherPermission implements Permission, Serializable {

	private static final long serialVersionUID = 1L;
	
	/*--------------------------------------------
    |             C O N S T A N T S             |
    ============================================*/
    protected static final String WILDCARD_TOKEN = "*";
    protected static final String PART_DIVIDER_TOKEN = ":";
    protected static final boolean DEFAULT_CASE_SENSITIVE = false;
    
    private String part;

    public AbsoluteMatcherPermission() {
	}
    
    public AbsoluteMatcherPermission(String permission) {
    	setPart(permission);
	}
    
    public AbsoluteMatcherPermission(String permission, boolean caseSensitive) {
    	setPart(permission, caseSensitive);
	}
    
    protected void setPart(String permission) {
        setPart(permission, DEFAULT_CASE_SENSITIVE);
    }

    protected void setPart(String permission, boolean caseSensitive) {
        if (permission == null || permission.trim().length() == 0) {
            throw new IllegalArgumentException("Absolute permission string cannot be null or empty. Make sure permission strings are properly formatted.");
        }

        permission = permission.trim();

        if (!caseSensitive) {
        	this.part = permission.toLowerCase();
        } else {
        	this.part = permission;
        }
    }
    
    protected String getPart(){
    	return this.part;
    }
    
	@Override
	public boolean implies(Permission p) {
		if (!(p instanceof AbsoluteMatcherPermission)) {
            return false;
        }
		
		AbsoluteMatcherPermission ap = (AbsoluteMatcherPermission) p;
		
		String otherPart = ap.getPart();
		
		if(otherPart.equals(getPart())){
			return true;
		}
		
		return false;
	}

}
